package com.tuanbiao.ui.auth;

import android.content.Context;
import android.content.Intent;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.hzjq.data.minbao.entity.AuthEntity;
import com.tuanbiao.base.mvp.BasePresenterActivity;
import com.tuanbiao.controllers.AuthController;
import com.tuanbiao.databinding.ActivityAuthDetailsBinding;
import com.tuanbiao.models.AuthModel;
import com.tuanbiao.presenter.auth.AuthDetailsPresenter;
import com.tuanbiao.ui.auth.adapter.AuthListDetailsAdapter;
import com.tuanbiao.utils.AuthLgComparator;
import com.tuanbiao.utils.ThreadMainTaskManager;

import java.util.ArrayList;
import java.util.Collections;

import io.reactivex.disposables.Disposable;

public class AuthDetailsActivity extends BasePresenterActivity<AuthDetailsPresenter, ActivityAuthDetailsBinding> implements AuthController.DetailsView {
    private AuthListDetailsAdapter authListDetailsAdapter;
    private Disposable sortDisposable;

    public static void start(Context context) {
        Intent starter = new Intent(context, AuthDetailsActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected ActivityAuthDetailsBinding getBindingView() {
        return ActivityAuthDetailsBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        binding.ivToolbarBack.setOnClickListener(getBackListener());
        binding.rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        authListDetailsAdapter = new AuthListDetailsAdapter();
        binding.rvContent.setAdapter(authListDetailsAdapter);
    }

    @Override
    protected AuthDetailsPresenter createPresenter() {
        return new AuthDetailsPresenter(new AuthModel(), this);
    }

    @Override
    public void showDetails(AuthEntity entity) {
        sortDisposable = ThreadMainTaskManager.startTask(new ThreadMainTaskManager.OnThreadMainTaskCallback<ArrayList<AuthEntity.Lgs.Lg>>() {

            @Override
            public ArrayList<AuthEntity.Lgs.Lg> doThreadTask() {
                ArrayList<AuthEntity.Lgs.Lg> lgs = entity.getLgs().getLg();
                Collections.sort(lgs,new AuthLgComparator());
                return lgs;
            }

            @Override
            public void doMainTask(ArrayList<AuthEntity.Lgs.Lg> lgs) {
                releaseSortDisposable();
                authListDetailsAdapter.setNewInstance(lgs);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseSortDisposable();
    }

    private void releaseSortDisposable(){
        if(sortDisposable != null && !sortDisposable.isDisposed()){
            sortDisposable.dispose();
        }
    }
}